const { Level } = require('level');
const path = require('path');
const config = require('./config');

class CacheManager {
    constructor() {
        this.db = null;
        this.memoryCache = new Map();
        this.cleanupTimer = null;
    }

    async init() {
        // 初始化LevelDB
        this.db = new Level(config.storage.path, { valueEncoding: 'json' });
        await this.db.open();
        
        // 从磁盘加载数据到内存
        await this.loadFromDisk();
        
        // 启动清理定时器
        this.startCleanupTimer();
        
        console.log('缓存管理器初始化完成');
    }

    async loadFromDisk() {
        try {
            const keys = [];
            for await (const key of this.db.keys()) {
                keys.push(key);
            }
            
            for (const key of keys) {
                try {
                    const data = await this.db.get(key);
                    if (data.expires && data.expires > Date.now()) {
                        this.memoryCache.set(key, data);
                    } else if (data.expires && data.expires <= Date.now()) {
                        // 删除过期数据
                        await this.db.del(key);
                    }
                } catch (error) {
                    console.error(`加载键 ${key} 失败:`, error.message);
                }
            }
            
            console.log(`从磁盘加载了 ${this.memoryCache.size} 个有效缓存项`);
        } catch (error) {
            console.error('加载缓存数据失败:', error.message);
        }
    }

    async get(key) {
        const data = this.memoryCache.get(key);
        
        if (!data) {
            return null;
        }
        
        // 检查是否过期
        if (data.expires && data.expires <= Date.now()) {
            await this.delete(key);
            return null;
        }
        
        return data.value;
    }

    async set(key, value, ttl = config.cache.defaultTTL) {
        const expires = ttl ? Date.now() + ttl : null;
        const data = { value, expires, updated: Date.now() };
        
        // 更新内存缓存
        this.memoryCache.set(key, data);
        
        // 持久化到磁盘
        try {
            await this.db.put(key, data);
        } catch (error) {
            console.error(`持久化键 ${key} 失败:`, error.message);
        }
    }

    async delete(key) {
        this.memoryCache.delete(key);
        
        try {
            await this.db.del(key);
        } catch (error) {
            if (!error.code === 'LEVEL_NOT_FOUND') {
                console.error(`删除键 ${key} 失败:`, error.message);
            }
        }
    }

    async clear() {
        this.memoryCache.clear();
        
        try {
            await this.db.clear();
        } catch (error) {
            console.error('清空缓存失败:', error.message);
        }
    }

    startCleanupTimer() {
        this.cleanupTimer = setInterval(() => {
            this.cleanupExpired();
        }, config.cache.cleanupInterval);
    }

    async cleanupExpired() {
        const now = Date.now();
        let cleaned = 0;
        
        for (const [key, data] of this.memoryCache.entries()) {
            if (data.expires && data.expires <= now) {
                this.memoryCache.delete(key);
                try {
                    await this.db.del(key);
                    cleaned++;
                } catch (error) {
                    console.error(`清理过期键 ${key} 失败:`, error.message);
                }
            }
        }
        
        if (cleaned > 0) {
            console.log(`清理了 ${cleaned} 个过期缓存项`);
        }
    }

    getStats() {
        return {
            memoryItems: this.memoryCache.size,
            diskPath: config.storage.path
        };
    }

    async close() {
        if (this.cleanupTimer) {
            clearInterval(this.cleanupTimer);
        }
        
        if (this.db) {
            await this.db.close();
        }
    }
}

module.exports = CacheManager;
